package belajarzk.action.master;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.util.GenericAutowireComposer;
import org.zkoss.zul.Borderlayout;
import org.zkoss.zul.Center;
import org.zkoss.zul.Grid;
import org.zkoss.zul.Hbox;
import org.zkoss.zul.Label;
import org.zkoss.zul.ListModel;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Row;
import org.zkoss.zul.RowRenderer;
import org.zkoss.zul.Rows;
import org.zkoss.zul.SimpleListModel;
import org.zkoss.zul.South;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Toolbar;
import org.zkoss.zul.Toolbarbutton;
import org.zkoss.zul.Window;

import belajarzk.common.Common;
import belajarzk.database.dao.DaoFactory;
import belajarzk.database.dao.MpropinsiDao;
import belajarzk.database.hibernate.HibernateUtil;
import belajarzk.database.model.Mpropinsi;
import belajarzk.ui.util.MyTolbarbutton;

public class MpropinsiAction extends GenericAutowireComposer {

	/**
	 * 
	 */
	private static final long serialVersionUID = 3786091220301468178L;
	private Window addWindow;
	private Grid grid;
	private Textbox searchnama;

	private Textbox idMPropinsi;
	private Textbox propinsi;;

	private Mpropinsi mpropinsi;

	@Override
	public void doAfterCompose(Component comp) throws Exception {
		// TODO Auto-generated method stub
		super.doAfterCompose(comp);
		if (session.getAttribute("usersTemp") == null) {
			execution.sendRedirect("../login.zul");
			return;
		}
		searchnama.focus();
		onSearchDefault(null);
	}

	public void onKeyListener(Event event) {

		System.out.println("event.getData() = " + event.getName());

	}

	class MpropinsiRenderer implements RowRenderer {

		@Override
		public void render(final Row arg0, Object arg1) throws Exception {
			// TODO Auto-generated method stub
			final Mpropinsi mpropinsi = (Mpropinsi) arg1;

			new Label(mpropinsi.getIdMPropinsi()).setParent(arg0);
			new Label(mpropinsi.getPropinsi()).setParent(arg0);

			Hbox hbox = new Hbox();
			hbox.setHeight("20px");
			Toolbarbutton button = new Toolbarbutton("", "/img/edit.gif");
			button.addEventListener("onClick", new EventListener() {
				@Override
				public void onEvent(Event arg0) throws Exception {
					init(mpropinsi);
					addWindow.setVisible(true);
					addWindow.focus();
					addWindow.onModal();
				}

			});
			button.setParent(hbox);

			button = new Toolbarbutton("", "/img/delete.gif");
			button.addEventListener("onClick", new EventListener() {
				@Override
				public void onEvent(Event s) throws Exception {
					Messagebox.show("Are you sure to delete this data?",
							Common.getBahasa("question"), Messagebox.OK
									| Messagebox.CANCEL,
							Messagebox.EXCLAMATION, new EventListener() {

								@Override
								public void onEvent(Event event)
										throws Exception {
									int i = new Integer(event.getData()
											.toString());
									if (i == Messagebox.OK) {
										try {
											MpropinsiDao mpropinsiDao = DaoFactory
													.getInstance()
													.getMpropinsiDao();
											// mpropinsiDao.beginTransaction();
											mpropinsiDao.delete(mpropinsiDao
													.merge(mpropinsi));
											// mpropinsiDao.commitTransaction();
											arg0.detach();
										} catch (Exception e) {
											e.printStackTrace();
											Messagebox
													.show("Cannot delete this data!");
										}

									}

								}
							});

				}
			});
			button.setParent(hbox);
			hbox.setParent(arg0);
		}

	}

	public void onAdd(Event event) throws Exception {
		init(new Mpropinsi());
		addWindow.setVisible(true);
		addWindow.focus();
		addWindow.onModal();
	}

	private void init(Mpropinsi mpropinsi) {

		EventListener onSave = new EventListener() {
			@Override
			public void onEvent(Event arg0) throws Exception {
				if (onSave(arg0)) {
					onSearchDefault(null);
					addWindow.setVisible(false);
				}
			}
		};

		this.mpropinsi = mpropinsi;
		addWindow
				.setTitle(mpropinsi.getIdMPropinsi() == null ? "Add New Province"
						: "Edit Existing Province");
		Common.clear(addWindow);
		Borderlayout borderlayout = new Borderlayout();
		Center center = new Center();
		center.setParent(borderlayout);
		center.setFlex(true);
		Grid grid = new Grid();
		grid.setParent(center);
		grid.setWidth("100%");
		grid.setHeight("100%");
		grid.setOddRowSclass("non-odd");

		Rows rows = new Rows();
		rows.setParent(grid);

		Row row = new Row();
		row.setStyle("border:0px;background: transparent;");
		row.setParent(rows);
		row.appendChild(new Label("Province Code"));
		row.appendChild(idMPropinsi = new Textbox(
				mpropinsi.getIdMPropinsi() == null ? "" : mpropinsi
						.getIdMPropinsi()));
		idMPropinsi.setCols(30);
		//idMPropinsi.setReadonly(true);

		row = new Row();
		row.setStyle("border:0px;background: transparent;");
		row.setParent(rows);
		row.appendChild(new Label("Name"));
		row
				.appendChild(propinsi = new Textbox(
						mpropinsi.getPropinsi() == null ? "" : mpropinsi
								.getPropinsi()));
		propinsi.setCols(30);
		propinsi.setConstraint("no empty");
		propinsi.addEventListener("onOK", onSave);

		South south = new South();
		south.setParent(borderlayout);
		south.setFlex(true);

		Toolbar hbox = new Toolbar();
		hbox.setHeight("40px");
		hbox.setParent(south);
		MyTolbarbutton cancel = new MyTolbarbutton("Cancel", "/img/cancel.gif");
		cancel.addEventListener("onClick", new EventListener() {
			@Override
			public void onEvent(Event arg0) throws Exception {
				addWindow.setVisible(false);
			}
		});
		cancel.setParent(hbox);
		MyTolbarbutton save = new MyTolbarbutton("Simpan", "/img/save.gif");
		save.addEventListener("onClick", onSave);
		save.setParent(hbox);
		borderlayout.setParent(addWindow);

	}

	public boolean onSave(Event event) throws Exception {

		MpropinsiDao mpropinsiDao = DaoFactory.getInstance().getMpropinsiDao();
		if (mpropinsi.getIdMPropinsi() != null) {
			mpropinsi = mpropinsiDao.load(mpropinsi.getIdMPropinsi());
		}
		mpropinsi.setPropinsi(propinsi.getValue().trim());

		//mpropinsiDao.beginTransaction();
		if (mpropinsi.getIdMPropinsi() != null) {
			mpropinsiDao.update(mpropinsi);
		} else {
			mpropinsi.setIdMPropinsi(idMPropinsi.getValue().trim());
			mpropinsiDao.save(mpropinsi);
		}
		//mpropinsiDao.commitTransaction();
		return true;
	}

	@SuppressWarnings("unchecked")
	public void onSearchDefault(Event event) {
		Session session = HibernateUtil.currentSession();
		List<Mpropinsi> mpropinsi = session.createCriteria(Mpropinsi.class)
				.addOrder(Order.asc("propinsi")).add(
						Restrictions.ilike("propinsi", searchnama.getValue(),
								MatchMode.ANYWHERE)).setMaxResults(
						Common.MAX_RESULT).list();
		ListModel strset = new SimpleListModel(mpropinsi);
		grid.setRowRenderer(new MpropinsiRenderer());
		grid.setModel(strset);
		grid.setFixedLayout(true);
		grid.renderAll();
		grid.setOddRowSclass("non-odd");
		session.close();
	}

}
